'use strict';
const Service = require('egg').Service;

const extend = require('extend2');

class RedisService extends Service {

  // 消息推送
  async sendPublish(pub_name, data) {
    const res = await this.app.redis.publish(pub_name, data);
    if (!res) await this.ctx.service.admin.rocordErrLog('Redis消息推送失败,频道：' + pub_name);
    return !!res;
  }

  // 获取网站配置
  async getSiteConfig(clear = false) {
    let config = await this.app.redis.get('site_config');
    if (!config || clear) {
      const shop_info = await this.ctx.service.config.systemConfig('shop_info');
      const sms = await this.ctx.service.config.systemConfig('sms');
      let new_config = extend(shop_info, sms);
      new_config = JSON.stringify(new_config);
      this.app.redis.set('site_config', new_config);
      config = new_config;
    }
    return JSON.parse(config);
  }

  // 获取model_id
  async getAdminAuthModid(key, clear = false){
    let moduleCount = await this.app.redis.hlen('admin_auth');
    let mod_id = 0;
    if(!moduleCount || clear){
      const mod = await this.ctx.model.Systemmodule.findAll({ // 权限查询匹配
        where: {
          level: 3
        }, attributes: [ 'mod_id','ctl','act' ], raw: true,
      });
      if(Array.isArray(mod) && mod.length){
        let setData = {}
        for(let item of mod){
          setData[`${item.ctl}-${item.act}`] = item.mod_id;
        }
        await this.app.redis.hmset('admin_auth',setData);
      }
    }
    mod_id = await this.app.redis.hget('admin_auth',key);
    return mod_id;
  }
}

module.exports = RedisService;
